<template>
  <view class="group-page">
    <!-- #ifdef APP-PLUS || MP-WEIXIN   -->
    <u-sticky offset-top="0">
      <view class="category">
        <view @click="handleCategory(item)" class="item" v-for="item in categoryList" :key="item.id">
          <view class="title" :class="{'active': currentIndex === item.id}">{{item.name}}</view>
        </view>
      </view>
    </u-sticky>
    <!-- #endif -->
    <!-- #ifdef H5   -->
    <view class="category">
      <view @click="handleCategory(item)" class="item" v-for="item in categoryList" :key="item.id">
        <view class="title" :class="{'active': currentIndex === item.id}">{{item.name}}</view>
      </view>
    </view>
    <!-- #endif -->
    <view class="category-children" v-if="categoryChildrenList.length > 0">
      <view @click="handleChildren(item)" class="item" v-for="item in categoryChildrenList" :key="item.id">
        <view class="name" :class="{'active': currentChildrenIndex === item.id}">{{item.name}}</view>
      </view>
    </view>
    <view class="main">
      <view class="nothing" v-if="list.length === 0">暂无相关信息...</view>
      <v-list :list="list" @handleLike="handleLike" />
    </view>
    <u-back-top bottom="180" :scroll-top="scrollTop" icon="arrow-up" :customStyle="{'opacity': '0.88'}"></u-back-top>
    <v-tab :selected="'/pages/material/index'" />
  </view>
</template>

<script>
import Tab from '../../components/tab'
import color from '@/config/color.js'
import config from '@/config/config.js'
import base64 from '../../util/base64'
import Material from '../../api/material'
import List from '@/sub_main/material/components/MaterialList'

import { goLogin } from '../../util/platform'

const materialModel = new Material()
export default {
  components: {
    'v-tab': Tab,
    'v-list': List
  },
  onLoad() {

    uni.hideTabBar({
      animation: false,
      success: () => {

      },
      fail: () => {

      }
    })
    uni.setNavigationBarTitle({
      title: '发现'
    })
    uni.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.activeColor,
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  },
  // 分享
  onShareAppMessage(res) {
    return {
      // title: '快递熊小二',
      path: '/pages/index/index?scene=' +
          (this.$store.getters['User/info'] ? this.$store.getters['User/info'].id : 0),
      // 这里还可以定义图片
      // imageUrl: '',
    }
  },
  onShow() {
    // console.log(this.queryList)
    const token = this.$store.getters['User/token']
    materialModel.isLogin({ token }).then(response => {
      let { data } = response
      data = base64.parse(data)
      console.log(data)
      if (!data.isLogin) {
        uni.showModal({
          title: '需要登录才能继续操作',
          confirmText: '立即登录',
          success: res => {
            if (res.confirm) {
              return goLogin()
            } else {
            }
          }
        })
      } else {
        // 称加载分类
        this.init()
        this.getCategory()
      }
    })
  },
  onHide() {
    // 一定要处理
    // uni.removeStorageSync('material-id')
    this.$store.dispatch('Order/set_material', null).then(() => {
      this.init()
    })
    // this.init()
  },
  // 加载更多,分页
  onReachBottom() {
    this.getList(true)
  },
  // 刷新
  onPullDownRefresh() {
    // onshow中处理, 不需要刷新
    this.init()
    // this.getList()
    // this.getCategory()
    uni.stopPullDownRefresh()
  },
  computed: {
    // 当前ID, 如果没有子ID就使用父ID
    currentId() {
      return this.currentChildrenIndex > 0
        ? this.currentChildrenIndex : this.currentIndex
    }
  },
  data() {
    return {
      baseUrl: config.baseUrl,
      activeColor: color.main_color,
      total: 0,
      queryList: {
        page: 0,
        pageSize: 20,
        busy: false,
        category_id: 0
      },
      categoryList: [],
      categoryChildrenList: [],
      currentIndex: 0,
      currentChildrenIndex: 0,
      // 作品列表
      list: [],
      scrollTop: 0,
    }
  },
  onPageScroll(e) {
    // console.log(e)
    this.scrollTop = e.scrollTop;
  },
  methods: {
    init() {
      // const id = uni.getStorageSync('material-id') || 0
      const id = this.$store.getters['Order/materialId']
      console.log('di', id)
      this.queryList = {
        page: 0,
        pageSize: 20,
        busy: false,
        category_id: id
      }
      this.list = []
      this.total = 0
    },
    // saveImage(url, list) {
    //   // 预览
    //   uni.previewImage({
    //     urls: list.map(x => config.baseUrl + x),
    //     current: config.baseUrl + url
    //   })
    // },
    // copyText(text) {
    //   uni.setClipboardData({
    //     // data: text,
    //     data: text.replace(/<[^>]*>?/gm, ''),
    //     success: () => {
    //       uni.showToast({
    //         icon: 'none',
    //         title: '复制成功'
    //       })
    //     }
    //   })
    // },
    getList(append = false) {
      if (this.queryList.busy === false) {
        this.queryList.page++
        this.loading = true
        this.queryList.busy = true
        uni.showLoading({
          title: '加载中...'
        })
        materialModel.getList({
          ...this.queryList,
          id: this.currentId
        }).then(response => {
          uni.hideLoading()
          let { data } = response
          data = base64.parse(data)
          if (data.list.length === 0) {
            this.queryList.busy = true
          } else {
            this.queryList.busy = false
            if (append) {
              this.list = this.list.concat(data.list)
            } else {
              this.list = data.list
            }
          }
          this.total = data.quantity
          // console.log(this.list.map(x => x.id))
          // console.log(this.list)
          uni.stopPullDownRefresh();
        }).finally(() => {
          uni.hideLoading()
        })
      }
    },
    // 获取分类
    getCategory() {
      materialModel.getCategory().then(response => {
        let { data } = response
        data = base64.parse(data)
        this.categoryList = data.list
        if (this.categoryList.length > 0) {
          // console.log(this.categoryList)
          let first
          // console.log(this.categoryList.find(x => +x.id === +this.queryList.category_id))
          const the = this.categoryList.find(x => +x.id === +this.queryList.category_id)
          if (the) {
            first = the
            console.log(first)
          } else {
            first = this.categoryList[0]
            // uni.removeStorageSync('material-id')
          }
          this.currentIndex = first.id
          if (first.children && first.children.length > 0) {
            this.categoryChildrenList = first.children
            this.currentChildrenIndex = first.children[0].id
            // 获取列表
            this.getList()
          }
        }
      })
    },
    handleCategory(item) {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 10
      })
      if (item.id === this.currentIndex) {
        return
      }
      this.init()
      this.currentChildrenIndex = 0
      this.currentIndex = item.id
      // 处理第1子项
      if (item.children && item.children.length > 0) {
        this.categoryChildrenList = item.children
        const first = item.children[0]
        this.currentChildrenIndex = first.id
      }
      this.getList()
    },
    handleChildren(item) {
      if (item.id === this.currentChildrenIndex) {
        return
      }
      this.init()
      this.currentChildrenIndex = item.id
      this.getList()
    },
    // 点赞
    handleLike(item) {
      const has_like = !item.has_like
      this.list.forEach(x => {
        if (x.id === item.id) {
          this.$set(x, 'has_like', has_like)
          if (has_like) {
            this.$set(x, 'like', item.like + 1)
          } else {
            if (item.like >= 1) {
              this.$set(x, 'like', item.like - 1)
            }
          }
        }
      })
      materialModel.saveLike({ ...item }).then(() => {
      })
    }
  }
}
</script>

<style scoped lang="scss">
.main {
  //font-size: 24rpx;
  padding: 20rpx 0;
  .nothing {
    color: #999999;
    font-size: 24rpx;
    //background: white;
    margin: 20rpx;
  }
}
.group-page {
  min-height: 100vh;
  background: #f3f5f7;
  //padding-bottom: 50px;
  padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
  .category, .category-children {
    font-size: 24rpx;
    background: #fdfdfd;
    display: flex;
    border-bottom: 1rpx solid #e7e7e7;
    align-items: center;
    justify-content: start;
    overflow-x: auto;
    //padding: 0 20rpx;
    //box-sizing: border-box;
    flex-wrap: wrap;
    .item {
      margin: 0 35rpx;
      //min-width: 120rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      .title, .name {
        font-size: 24rpx;
        color: #898989;
        height: 80rpx;
        line-height: 80rpx;
        &.active {
          color: #313131;
          font-weight: 700;
        }
      }
    }
  }
  .category {
    justify-content: center;
  }
  .category-children {
    border: none;
  }
  //.list {
  //  padding: 20rpx;
  //  .item {
  //    background: white;
  //    padding: 10px;
  //    border-radius: 5px;
  //    margin-bottom: 10px;
  //    .time {
  //      color: #cccccc;
  //      margin-bottom: 10px;
  //    }
  //    .title {
  //      font-weight: 700;
  //      font-size: 26rpx;
  //      margin-bottom: 10px;
  //      line-height: 1.3em;
  //    }
  //    .btn {
  //      width: 200rpx;
  //      margin-bottom: 10px;
  //      margin-top: 20rpx;
  //    }
  //    .i {
  //      font-size: 24rpx;
  //      color: #cccccc;
  //      margin-top: 20rpx;
  //    }
  //    .t {
  //      margin: 10px 0;
  //      color: #999999;
  //    }
  //    .image {
  //      //background: red;
  //      image, img {
  //        max-width: 100%;
  //      }
  //    }
  //  }
  //}
}
</style>
